package com.kakarote.crm9.erp.qd.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.kakarote.crm9.common.config.redis.Redis;
import com.kakarote.crm9.common.config.redis.RedisManager;
import com.kakarote.crm9.utils.HttpClientUtil;

public class QdController extends Controller {
    private String appid = "201113782";
    private String appSecret = "f5blTgAeWkY1BUOn";

    /**
     * 获取ticket
     */
    public void getTicket(@Para("kfext")String kfext){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("kfext",kfext);
        jsonObject.put("type","jssdk");
        String s = HttpClientUtil.doPost("https://api.qidian.qq.com/cgi-bin/jssdk/ticket/getticket?access_token=" + getAccessToken(), jsonObject);
        renderJson(s);
    }
    /**
     * 获取access_token
     */
    public String getAccessToken() {
        Redis redis= RedisManager.getRedis();
        String accessToken = "";
        if(redis.get("qd_access_token")!=null) {
            accessToken = redis.get("qd_access_token");
        } else {
            String result = HttpClientUtil.doGet("https://api.qidian.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appSecret, "utf-8");
            JSONObject jsonObject = JSON.parseObject(result);
            accessToken = String.valueOf(jsonObject.get("access_token"));
            Integer expiresIn = Integer.valueOf(String.valueOf(jsonObject.get("expires_in")));
            redis.setex("qd_access_token",expiresIn,accessToken);
        }
        return accessToken;
    }
}
